package com.en.common;


import com.alibaba.fastjson2.JSON;
import com.en.response.AppException;
import com.en.response.ErrorCodeMsgEnum;
import okhttp3.*;
import okhttp3.internal.http2.Header;

import java.util.Map;

/**
 * ClassName: Utils
 * Package: com.tencent.wxcloudrun.common
 * Description:
 *
 * @Date: 2023/1/31 7:39 PM
 * @Author: wht
 */
public class Utils {


    public static String httpGet(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.SERVICE_ERROR);
        }
    }

    public static String httpPost(String url, Map<String, String> headers, Map body) {
        try {
            Request.Builder builder = new Request.Builder();
            builder.url(url);

//            header -------------------------------------------
            headers.forEach(builder::addHeader);


//            body -------------------------------------------
            MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = RequestBody.create(JSON_TYPE, JSON.toJSONString(body));
            builder.post(requestBody);


            // 发送请求 ----------------------------------------------------
            Response response = client.newCall(builder.build()).execute();
            return response.body().string();
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.SERVICE_ERROR);
        }
    }


}
